package com.douglas.managesystem.controller.admin;


import com.douglas.managesystem.common.*;
import com.douglas.managesystem.controller.BaseController;
import com.douglas.managesystem.entity.system.Menu;
import com.douglas.managesystem.entity.system.SysLogger;
import com.douglas.managesystem.service.admin.UserService;
import com.douglas.managesystem.service.system.MenuService;
import com.douglas.managesystem.service.system.SysLoggerService;
import com.douglas.managesystem.vo.UserVO;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.util.List;
import java.util.Random;



/**
 * @Description 管理系统登录入口
 * @Author 以梦为馬 <Douglas1314@126.com>
 * @Version V1.0.0
 * @Date 2020-10-23 15:13
 **/
@SuppressWarnings("all")
@Controller
@RequestMapping("/admin")
public class LoginUserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginUserController.class);

    /**
     * 用户业务层
     */
    @Autowired
    private UserService userService;


    @Autowired
    private MenuService menuService;

    @Autowired
    private SysLoggerService sysLoggerService;

    @Value("${filepath}")
    public String profilepath;

    /**
     * 1.去登陆页面
     *
     * @return
     */
    @GetMapping("toLogin")
    public String toLogin() {
        Random random = new Random();
        int k = random.nextInt();
        int j = Math.abs(k % 10);
        if (j % TWO == 0) {
            return "admin/login1";
        } else {
            return "admin/login";
        }

    }

    /**
     * 2.请求登录-登录验证
     *
     * @param user
     * @return
     */
    @RequestMapping("/user/login")
    @ResponseBody
    public ResponseResult login(@RequestBody UserVO user,HttpServletRequest re) {
//        InetAddress ia = null;
        /*String ip = null;
        try {
             ip = InetAddress.getLocalHost().getHostAddress();
            //得到服务器的ID
            logger.info("ip:" + ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String check = user.getCheck();
        String code = PropertiesUtil.readValue(profilepath, ip);*/
//        String check = user.getCheck();
//        String code = session.getAttribute("code_session").toString();
//        String code = RequestHolder.getSession().getAttribute("code_session").toString();
        /*Cookie[] cookies = re.getCookies();
        String code = null;
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals("code_session")){
                 code = cookie.getValue();
            }
        }*/
        /*logger.info("session的验证码:" + code);
        logger.info("用户的验证码：" + check);
        check = check.toLowerCase();
        code = code.toLowerCase();*/
        ResponseResult responseResult = new ResponseResult();

        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            responseResult.setInfo("用户名或密码不能为空！");
            return responseResult;
        }
        /*if (StringUtils.isEmpty(user.getCheck())) {
            responseResult.setInfo("验证码不能为空!");
            return responseResult;
        }
        if (!code.equals(check)) {
            responseResult.setInfo("验证码错误！");
            return responseResult;
        }*/
        UserVO userVO = userService.loginUser(user);
        if (!StringUtils.isEmpty(userVO.getStatus()) && userVO.getStatus().toString().equals(NumberEnum.ZERO.getCode())) {
            responseResult.setInfo("Sorry···账号已禁用,请联系管理员！");
            return responseResult;
        }
        //1.判断用户标识等于0的话，为用户名不存在或密码错误，直接返回
        if (userVO.getVcode().equals(NumberEnum.ZERO.getCode())) {
            responseResult.setInfo("用户不存在或密码错误！");
            return responseResult;
        }
        responseResult.setData(userVO);
        responseResult.setInfo("登陆成功");
        responseResult.setSuccess(true);
        session.setAttribute("loginUser", userVO);
        //记录日志
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取request
        HttpServletRequest request = attr == null ? null : attr.getRequest();
        SysLogger sysLogger = new SysLogger();
        sysLogger.setId(UUIDUtils.getCharAndNumr(10));
        sysLogger.setBrowser(HttpRequestUtils.getBrowser(request));
        sysLogger.setIp(HttpRequestUtils.getRequestAddr(request));
        sysLogger.setModule(HttpRequestUtils.getPlatform(request));
        sysLogger.setOperUser(userVO.getUsername());
        sysLogger.setLevel("info");
        sysLogger.setPlatform(HttpRequestUtils.getPlatform(request));
        sysLogger.setOperType(userVO.getUserRole());
        sysLogger.setCreateBy(userVO.getId());
        sysLoggerService.insert(sysLogger);
        return responseResult;
    }

    /**
     * 2.进入主页面
     *
     * @return
     */
    @GetMapping("/user/toIndex")
    public ModelAndView toIndex(ModelMap modelMap) {
        ModelAndView mv = new ModelAndView();
        System.out.println(session.getAttribute("loginUser"));
        UserVO user = (UserVO) session.getAttribute("loginUser");
        List<Menu> menus = menuService.selectMenuByUserId(user.getId());
        modelMap.put("menus", menus);
        mv.setViewName("admin/index");
        return mv;
    }

    /**
     * 3.用户登出
     *
     * @return
     */
    @GetMapping("/user/logout")
    public String logout() {
        session.removeAttribute("loginUser");
        return "redirect:/admin/toLogin";
    }

    /**
     * 4.日志列表
     *
     * @param model
     * @param entity
     * @return
     */
    @GetMapping("/logger/list")
    public String toLogger(Model model, SearchEntity entity) {
        PageInfo<SysLogger> page = sysLoggerService.queryListByPage(entity);
        model.addAttribute("sysLogger", page);
        return "admin/logger/list";
    }

    /**
     *  * 生成验证码
     *  
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            String randcode = randomValidateCode.getRandcode(request, response);//输出验证码图片方法
//            request.getSession().setAttribute("code_session",randcode);
            /*Cookie codeCookie = new Cookie("code_session", randcode);*/
            /*codeCookie.setMaxAge(60*5);
            codeCookie.setPath("/");
            response.addCookie(codeCookie);*/
            System.out.println("登录前code："+randcode);


            /*String ip = null;
            try {
                 ip = InetAddress.getLocalHost().getHostAddress();
                //得到服务器的ID
                logger.info("ip:" + ip);
            } catch (Exception e) {
                e.printStackTrace();
            }
            PropertiesUtil.writeProperties(ip,randcode);*/

        } catch (Exception e) {
            logger.error("获取验证码失败>>>> ", e);
        }

    }


}
